import React from 'react';
import { useTranslation } from 'react-i18next';
import { NetworkStatus } from '@apollo/client';
import {
  Box,
  CardBase,
  CardSection,
  Empty,
  LoadingPlaceholder,
  ThemeColorType,
  UsageCard,
} from '@nova-hf/ui';
import { MainColorType } from '@nova-hf/ui/umd/ts/src/styles/vars.css';
import { ErrorBanner } from 'beta/components/error/ErrorBanner';
import UI from 'beta/store/ui';
import { formatDate } from 'beta/utils/helpers';
import { inject, observer } from 'mobx-react';
import { useRouter } from 'next/router';
import { Maybe, UsageCounter, useContractUsageQuery } from 'typings/graphql';

import { SectionHeader } from '../../comoponents/SectionHeader';

type UsageSummaryProps = {
  contractId: string;
  nationalId: string;
  color: ThemeColorType;
  ui?: UI;
  isActive?: boolean;
};

const UsageSummary = ({ contractId, color, ui, isActive }: UsageSummaryProps) => {
  const { t } = useTranslation(['service', 'errors']);
  const router = useRouter();
  const serviceId = router.query.serviceId ?? '';
  const { data, error, loading, refetch, networkStatus } = useContractUsageQuery({
    variables: {
      input: {
        serviceId: serviceId as string,
        id: contractId,
      },
    },
    nextFetchPolicy: 'cache-and-network',
    notifyOnNetworkStatusChange: true,
    skip: !isActive,
  });

  const contractUsage = data?.contractUsage ? data.contractUsage[0] : undefined;

  const contractUsageCounters = contractUsage?.usageCounters
    ? contractUsage.usageCounters
    : undefined;

  if (loading || error) {
    return (
      <ErrorBanner
        eyebrowTexts={[
          t('errors:usageSummary.eyebrows.1'),
          t('errors:usageSummary.eyebrows.2'),
          t('errors:usageSummary.eyebrows.3'),
        ]}
        titles={[
          t('errors:usageSummary.titles.1'),
          t('errors:usageSummary.titles.2'),
          t('errors:usageSummary.titles.3'),
        ]}
        descriptions={[
          t('errors:usageSummary.descriptions.1'),
          t('errors:usageSummary.descriptions.2'),
          t('errors:usageSummary.descriptions.3'),
        ]}
        icon="zap"
        color={ui?.serviceColor ?? 'attention'}
        showLoading={loading || networkStatus === NetworkStatus.refetch}
        refetchButton={{
          text: t('errors:buttons.refresh'),
          icon: 'refresh',
          onClick: () => refetch(),
        }}
        loadingComponent={
          <CardBase backgroundColor="white" boxShadow="small">
            <CardSection>
              <Box marginBottom={1}>
                <LoadingPlaceholder height={2} width="1/12" />
              </Box>
              <Box marginBottom={2}>
                <LoadingPlaceholder height={5} width="3/12" />
              </Box>
              <Box paddingBottom={1}>
                <LoadingPlaceholder height={2} width="11/12" />
              </Box>
            </CardSection>
          </CardBase>
        }
      />
    );
  }

  const remainingPercentage = (usageCounter: Maybe<UsageCounter>) => {
    if (!usageCounter?.isInfinite) return 100;
    if (usageCounter.remaining) {
      return usageCounter.remaining;
    } else return 0;
  };

  const priceAmount = t('usageSummary.priceAmountLabel');

  return (
    <Box width="100%">
      <SectionHeader headerTitle={t('usageSummary.title')} />
      {!contractUsageCounters?.length ? (
        <Empty
          icon="search"
          color={color}
          subtitle={`Engin notkun fannst fyrir ${formatDate(new Date(), 'MMMM')}`}
        />
      ) : (
        <>
          {contractUsageCounters?.map((usageCounter, i) => {
            return (
              <Box marginBottom={4} key={i}>
                <UsageCard
                  color={color as MainColorType}
                  price={{
                    amount: priceAmount,
                  }}
                  progressBar={{
                    percentage: remainingPercentage(
                      usageCounter?.__typename === 'UsageCounter' ? usageCounter : null,
                    ),
                    thickness: 2,
                  }}
                  title={usageCounter?.title ?? ''}
                  usage={{
                    total: {
                      amount: usageCounter?.included?.quantity ?? '',
                      unit: usageCounter?.included?.unit ?? '',
                      isinfinite: usageCounter?.isInfinite || false,
                    },
                    used: {
                      amount:
                        usageCounter?.included?.quantity && usageCounter?.remaining?.quantity
                          ? Math.round(
                              usageCounter?.included?.quantity - usageCounter?.remaining?.quantity,
                            )
                          : '',
                      description: t('usageSummary.usedDescription'),
                      unit: usageCounter?.included?.unit ?? '',
                    },
                    remaning: {
                      amount: usageCounter?.remaining?.quantity ?? '',
                      description: t('usageSummary.remainingDescription'),
                      unit: usageCounter?.remaining?.unit ?? '',
                      isinfinite: usageCounter?.isInfinite || false,
                    },
                  }}
                  withBorder
                />
              </Box>
            );
          })}
        </>
      )}
    </Box>
  );
};

export default inject('ui')(observer(UsageSummary));
